package com.lanou.renrenxin.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMError;
import com.easemob.chat.EMChatManager;
import com.easemob.exceptions.EaseMobException;
import com.lanou.renrenxin.R;
import com.lanou.renrenxin.base.BaseActivity;
import com.lanou.renrenxin.tools.LogUtils;
import com.parse.ParseAnalytics;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.SaveCallback;

import java.io.ByteArrayOutputStream;

/**
 * Created by dllo on 16/3/2.
 */
public class RegisterActivity extends BaseActivity implements View.OnClickListener {
    private Button register;
    private TextView textViewOne,textViewTwo;
    private EditText usernameEt,passWordEt,passWordAgainEt;
    private Context context;
    private Handler handle;
    private String username,passWord;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ParseAnalytics.trackAppOpenedInBackground(getIntent());
        setContentView(R.layout.activity_register);
        //加动画
        overridePendingTransition(R.anim.activity_from_right, R.anim.activity_in);

        textViewOne = (TextView) findViewById(R.id.register_renRenXin);
        textViewTwo = (TextView) findViewById(R.id.register_jiShiTongXun);
        textViewOne.setRotationY(20);
        textViewTwo.setRotationY(-20);
        register = (Button) findViewById(R.id.register);
        register.setOnClickListener(this);

        context = getApplicationContext();
        usernameEt = (EditText) findViewById(R.id.userName_register);
        passWordEt = (EditText) findViewById(R.id.passWord_register);
        passWordAgainEt = (EditText) findViewById(R.id.passWordAgain_register);
        findViewById(R.id.register).setOnClickListener(this);

        handle = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                switch (message.what){
                    case 0:
                        Toast.makeText(getApplicationContext(),"网络异常，请检查网络！",Toast.LENGTH_SHORT);
                        break;
                    case 1:
                        Toast.makeText(getApplicationContext(), "用户已存在！", Toast.LENGTH_SHORT).show();
                        break;
                    case 2:
                        Toast.makeText(getApplicationContext(), "注册失败，无权限！", Toast.LENGTH_SHORT).show();
                        break;
                    case 3:
                        Toast.makeText(getApplicationContext(), "注册失败" + message.obj, Toast.LENGTH_SHORT).show();
                }
                return false;
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.register:
                addData();
                //在服务器中存储新注册的用户
                addServier();
                break;
        }
    }

    //用户数据添加服务器
    private void addServier() {
        ParseObject po = new ParseObject("UserInfo");
        //用户头像
        Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.mipmap.chatblue);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] data = stream.toByteArray();

        ParseFile pf = new ParseFile(username,data);
        pf.saveInBackground();
        //用户名字与密码
        po.put("user_name", username);
        po.put("user_password", passWord);
        po.put("user_photo", pf);
        po.saveInBackground(new SaveCallback() {
            @Override
            public void done(ParseException e) {
                Toast.makeText(context, "注册成功", Toast.LENGTH_SHORT).show();
                LogUtils.i("添加到服务器中");
            }
        });
    }

    private void addData() {
         username = usernameEt.getText().toString().trim();
         passWord = passWordEt.getText().toString().trim();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 调用sdk注册方法
                    Log.d("MainActivity", username);
                    Looper.prepare();
                    EMChatManager.getInstance().createAccountOnServer(username, passWord);
                    Looper.loop();

                } catch (final EaseMobException e) {
                    //注册失败
                    int errorCode = e.getErrorCode();
                    if (errorCode == EMError.NONETWORK_ERROR) {

                        handle.sendEmptyMessage(0);
                    } else if (errorCode == EMError.USER_ALREADY_EXISTS) {

                        handle.sendEmptyMessage(1);
                    } else if (errorCode == EMError.UNAUTHORIZED) {

                        handle.sendEmptyMessage(2);
                    } else {
//                        Toast.makeText(getApplicationContext(), "注册失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        Message msg = new Message();
                        msg.what =3;
                        msg.obj =e.getMessage();
                        handle.sendEmptyMessage(3);
                    }

                }
            }
        }).start();
        Intent intent = new Intent(this,LoginActivity.class);
        intent.putExtra("name", username);
        if (usernameEt.getText().length() > 0 && passWordEt.getText().length() > 0
                && passWordAgainEt.getText().length() > 0) {
            startActivity(intent);
            finish();
        } else {
            Toast.makeText(RegisterActivity.this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
        }
    }
}
